package com.jic.market.impl;

import com.alibaba.excel.metadata.BaseRowModel;
import com.beust.jcommander.internal.Lists;
import com.google.common.collect.Maps;
import com.jic.common.base.vo.AdminOperate;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.base.vo.enums.DeptTypeEnums;
import com.jic.market.common.constant.DbEffectConstant;
import com.jic.market.common.constant.PatchGrouponStockLmtConstant;
import com.jic.market.common.enums.*;
import com.jic.market.common.exception.MarketErrorCodeEnum;
import com.jic.market.common.exception.MarketException;
import com.jic.market.common.util.ListUtils;
import com.jic.market.common.util.LoginService;
import com.jic.market.entity.*;
import com.jic.market.entity.mutex.MutexProductEntity;
import com.jic.market.entity.mutex.MutexResultContext;
import com.jic.market.impl.excel.ExcelListenerData;
import com.jic.market.impl.excel.ExcelUtil;
import com.jic.market.impl.excel.GrouponExcelListener;
import com.jic.market.mapper.PatchGrouponMpEntityMapper;
import com.jic.market.model.LimitQueryUniqueCondition;
import com.jic.market.model.MpQueryUniqueCondition;
import com.jic.market.orm.Pagination;
import com.jic.market.request.PatchGouponProductRequest;
import com.jic.market.request.PatchGroupProductAddAllProductRequest;
import com.jic.market.request.PatchGroupProductSaveV2Request;
import com.jic.market.request.PatchGroupPromotionProductQueryListV2Request;
import com.jic.market.request.manager.goods.GoodsSkuQueryRequest;
import com.jic.market.request.manager.patchgroup.PatchGrouponProductSkuCountRequest;
import com.jic.market.request.rest.groupon.GrouponProductListRequest;
import com.jic.market.response.PatchGroupProductV2Response;
import com.jic.market.response.PatchGroupSonProductV2Response;
import com.jic.market.response.manager.goods.*;
import com.jic.market.response.manager.product.GoodsSkuQueryResponse;
import com.jic.market.response.manager.product.GoodsSpuPageQueryResponse;
import com.jic.market.response.rest.groupon.GrouponProductInfo;
import com.jic.market.service.PatchGroupMerchantProductService;
import com.jic.market.service.PatchGrouponStockLmtService;
import com.jic.market.service.PromotionMutexService;
import com.jic.market.service.mutex.MutexService;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.GoodsPageQueryRequest;
import com.jic.product.after.response.ProductStoreInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * 促销-拼团 商家商品服务
 *
 * @author guohuayong
 * @date 2020/2/24 17:40
 **/
@Service
@Slf4j
public class PatchGroupMerchantProductServiceImpl implements PatchGroupMerchantProductService {
    @Resource
    private PatchGrouponMpEntityMapper curMapper;

    @Resource
    private LoginService loginService;
    @Autowired
    private PatchGrouponStockLmtService stockLmtEntityService;

    @Autowired
    MutexService mutexService;

    @Autowired
    PromotionMutexService promotionMutexService;
    @Resource
    private ProductListApi productListApi;


    @Override
    public PatchGrouponMpEntity query(PatchGrouponMpEntity mpEntityCondition) {
        PatchGrouponMpEntity mpEntity = curMapper.query(mpEntityCondition);
        return mpEntity;
    }

    @Override
    public Integer saveBatch(List<PatchGouponProductRequest> productList) {
        if (null == productList || productList.isEmpty()) {
            throw new MarketException(MarketErrorCodeEnum.PARAM_ERROR);
        }

        for (int i = 0; i < productList.size(); i++) {
            PatchGouponProductRequest temp = productList.get(i);

            PatchGrouponMpEntity entity = curMapper.getByPromotionIdAndMpId(temp.getPromotionId(), temp.getMpId());
            if (null != entity) {
                continue;
            }

            int ret = curMapper.insert(buildPatchGrouponMpEntity(temp));
            if (ret < 1) {
                throw new MarketException(MarketErrorCodeEnum.SQL_ERROR);
            }
        }

        return productList.size();
    }

    /**
     *
     * @param productList
     * @return
     */
    @Override
    public Integer saveBatchV2(List<PatchGroupProductSaveV2Request> productList) {
        log.info("-----进入批量保存促销活动商品--远程调用商品服务，查询子商品--productIds:{}-----");

        Long promotionId =null;
        GoodsPageQueryRequest goodsSkuQueryRequest =new GoodsPageQueryRequest();
        List<Long> goodsSpuIds =new ArrayList<>();
        for (PatchGroupProductSaveV2Request x : productList) {
            goodsSpuIds.add(x.getGoodsSpuId());
            promotionId =x.getPromotionId();

        }

        goodsSkuQueryRequest.setSpuIds(goodsSpuIds);

        log.info("-----进入批量保存促销活动商品--远程调用商品服务开始，查询子商品--goodsSpuIds:{}-----",goodsSpuIds);
//        RestResult<List<QueryGoodsInfoResponse>> listRestResult =
//                goodsQueryService.queryByGoodsSpuIds(goodsSkuQueryRequest);

        List<ProductStoreInfo> productAfterList = productListApi.queryProductBySpuId(goodsSkuQueryRequest);

        log.info("-----进入批量保存促销活动商品--远程调用商品服务完毕，查询子商品--goodsSpuIds:{}-----",goodsSpuIds);

        // 批量保存商品
//        List<QueryGoodsInfoResponse> productAfterList = listRestResult.getData();

        if (productAfterList == null || productAfterList.size() ==0){
            log.info("-----进入批量保存促销活动商品--当前并未查到商品用于促销--promotionId:{}---",promotionId);
            return 2;
        }

        // 组装productList
        List<PatchGrouponMpEntity> productListNew = new ArrayList<>();

        //获取互斥结果
        final MutexResultContext mutexResultContext = getMutexResultContext(promotionId, productAfterList);
        final Map<Long, Set<MutexProductEntity>> mutexPromotionProducts = mutexResultContext.getMutexPromotionProducts();
        final Set<Long> mutexList = mutexResultContext.getMutexList();
        final Map<Long, Long> mutexMpIdMap = Maps.newHashMap();

        for (ProductStoreInfo queryGoodsInfoResponse : productAfterList) {
            ProductStoreInfo productAfterResponse = queryGoodsInfoResponse;
            List<ProductStoreInfo> productAfterSonResponse = queryGoodsInfoResponse.getChildren();

            /**
             * 保存 spu商品，赋值类型，数据库字段type_of_product，参见
             * ({@link com.jic.market.common.enums.TypeOfProductEnum})
             */

            log.info("--------spu商品--------");

//            PatchGrouponMpEntity entity = curMapper.getByPromotionIdAndMpId(promotionId, productAfterResponse.getId());

            MpQueryUniqueCondition mpQueryUniqueCondition =new MpQueryUniqueCondition();
            mpQueryUniqueCondition.setMpId(productAfterResponse.getId());
            mpQueryUniqueCondition.setPromotionId(promotionId);
            mpQueryUniqueCondition.setStoreId(productAfterResponse.getStoreId());
            mpQueryUniqueCondition.setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
            PatchGrouponMpEntity entity = curMapper.getMpQueryUnique(mpQueryUniqueCondition);
            if (null == entity) {
                PatchGrouponMpEntity productEntity =
                        assembleSpuPromotionProduct(promotionId, productAfterResponse);
                productEntity.setMutexFlag(MutexFlagEnum.UN_MUTEX.getCode());
                productListNew.add(productEntity);
            }else{
                //更新
                PatchGrouponMpEntity updateParam = new PatchGrouponMpEntity();
                updateParam.setId(entity.getId());
                updateParam.setMutexFlag(MutexFlagEnum.UN_MUTEX.getCode());
//                if(mutexList.contains(productAfterResponse.getId())){
//                    mutexMpIdMap.put(productAfterResponse.getId(), updateParam.getId());
//                }
                curMapper.update(updateParam);
            }

            log.info("--------sku商品--------");
            for (ProductStoreInfo afterSonResponse : productAfterSonResponse) {
//                PatchGrouponMpEntity entitySon = curMapper.getByPromotionIdAndMpId(promotionId, afterSonResponse.getId());
                MpQueryUniqueCondition mpQueryUniqueConditionSon =new MpQueryUniqueCondition();
                mpQueryUniqueConditionSon.setMpId(afterSonResponse.getId());
                mpQueryUniqueConditionSon.setPromotionId(promotionId);
                mpQueryUniqueConditionSon.setStoreId(afterSonResponse.getStoreId());
                mpQueryUniqueConditionSon.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
                PatchGrouponMpEntity entitySon = curMapper.getMpQueryUnique(mpQueryUniqueConditionSon);
                if (null == entitySon) {
                    PatchGrouponMpEntity productEntityForSon =
                            assembleSkuPromotionProduct(promotionId, productAfterResponse, afterSonResponse);
                    productEntityForSon.setMutexFlag(mutexList.contains(afterSonResponse.getId()) ? MutexFlagEnum.MUTEX.getCode() : MutexFlagEnum.UN_MUTEX.getCode());
                    productListNew.add(productEntityForSon);
                }else{
                    //更新
                    PatchGrouponMpEntity updateParam = new PatchGrouponMpEntity();
                    updateParam.setId(entitySon.getId());
                    updateParam.setMutexFlag(mutexList.contains(afterSonResponse.getId()) ? MutexFlagEnum.MUTEX.getCode() : MutexFlagEnum.UN_MUTEX.getCode());
                    curMapper.update(updateParam);
                    if(mutexList.contains(afterSonResponse.getId())){
                        mutexMpIdMap.put(afterSonResponse.getId(), updateParam.getId());
                    }
                }
            }
        }

        // 批量保存 实体
        List<PatchGrouponMpEntity> productListDB = this.saveBatchEntity(productListNew);
        if (productListDB ==null){
            // 无可保存的商品
            return 2;
        }
        productListDB.forEach(p->{
            if(p.getMutexFlag() == 1){
                mutexMpIdMap.put(p.getMpId(), p.getId());
            }
        });
        //插入互斥表
        inserMutex(mutexPromotionProducts, mutexMpIdMap);

        // 用于添加到patch_groupon_stock_lmt ，需要指定TypeOfProduct为GOODS:商品
        log.info("----进入批量保存促销活动商品--添加促销商品的限制项--当前促销id:{}--",promotionId);
        List<PatchGrouponStockLmtEntity> lmtEntities = new ArrayList<>();

        log.info("----保存limit----->{}",productListDB);
        for (PatchGrouponMpEntity promotionProduct : productListDB){
//            PatchGrouponStockLmtEntity dbEntity = stockLmtEntityService.getEntityByPromotionIdAndMpId(
//                    promotionProduct.getPromotionId(), promotionProduct.getMpId());

            LimitQueryUniqueCondition limitCondition =new LimitQueryUniqueCondition();
            limitCondition.setStoreId(promotionProduct.getStoreId());
            limitCondition.setTypeOfProduct(promotionProduct.getTypeOfProduct());
            limitCondition.setPromotionId(promotionId);
            limitCondition.setMpId(promotionProduct.getMpId());
            PatchGrouponStockLmtEntity dbEntity =
                    stockLmtEntityService.getEntityLimitQueryUniqueCondition(limitCondition);

            if(dbEntity != null){
                continue;
            }
            PatchGrouponStockLmtEntity limitEntity =new PatchGrouponStockLmtEntity();
            limitEntity.setPatchGrouponMpId(promotionProduct.getId());
            limitEntity.setLimitType(LimitTypeEnum.GOODS.getCode());
            limitEntity.setRefPatchGrouponTheme(promotionProduct.getPromotionId());
            limitEntity.setMerchantId(promotionProduct.getMerchantId());
            limitEntity.setMerchantProductId(promotionProduct.getMpId());
            limitEntity.setMpCode(promotionProduct.getMpCode());
            limitEntity.setTypeOfProduct(promotionProduct.getTypeOfProduct());
            limitEntity.setStoreId(promotionProduct.getStoreId());
            //
            limitEntity.setTypeOfProduct(promotionProduct.getTypeOfProduct());
//            limitEntity.setStoreName(promotionProduct.getStoreName());
            limitEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            limitEntity.setMerchantProductName(promotionProduct.getMpName());
            limitEntity.setRuleType(PatchGrouponStockLmtConstant.RuleType.SHARE.getCode());

            // 限制值的初始化
            limitEntity.setGrouponPrice(null);
            limitEntity.setChannelMerchantLimit(null);
            limitEntity.setChannelStoreLimit(null);
            limitEntity.setIndividualLimit(null);
            limitEntity.setOrderLimit(null);
            limitEntity.setStockLimit(null);
            lmtEntities.add(limitEntity);
            //stockLmtEntityService.addPromotionLimitRule(limitEntity);
        }
        if(CollectionUtils.isNotEmpty(lmtEntities)){
            stockLmtEntityService.insertBatch(lmtEntities);
        }


        return null;
    }

    private void inserMutex(Map<Long, Set<MutexProductEntity>> mutexPromotionProducts,  Map<Long, Long> mutexMpIdMap){
        //插入互斥表
        mutexPromotionProducts.entrySet().forEach(e->{
            Set<MutexProductEntity> mutexProductEntitySet = e.getValue();
            promotionMutexService.deleteByPromotionProductId(mutexMpIdMap.get(e.getKey()));
            List<PromotionMutex> collect = mutexProductEntitySet.stream().map(m -> {
                return new PromotionMutex()
                        .setPromotionId(m.getPromotionId())
                        .setPromType(m.getPromType())
                        .setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode())
                        .setPromotionMerchantProductId(mutexMpIdMap.get(e.getKey()));
            }).collect(Collectors.toList());
            promotionMutexService.insertBatch(collect);
//            mutexProductEntitySet.forEach(m->{
//                promotionMutexService.insert(
//                        new PromotionMutex()
//                                .setPromotionId(m.getPromotionId())
//                                .setPromType(m.getPromType())
//                                .setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode())
//                                .setPromotionMerchantProductId(mutexMpIdMap.get(e.getKey()))
//                );
//            });
        });
    }
    /**
     * 获取互斥结果
     * @param promotionId
     * @param goodsInfoResponseList
     * @return
     */
    private MutexResultContext getMutexResultContext(Long promotionId, List<ProductStoreInfo> goodsInfoResponseList) {
        final List<Long> productList = Lists.newArrayList();
        goodsInfoResponseList.forEach(spu->{
            //productList.add(spu.getGoodsSpuInfo().getId());
            List<ProductStoreInfo> goodsSkuInfoList = spu.getChildren();
            if (goodsSkuInfoList != null && !goodsSkuInfoList.isEmpty()){
                goodsSkuInfoList.forEach(sku->{
                    productList.add(sku.getId());
                });
            }

        });
        return mutexService.doProcessMutexByPatch(promotionId, productList);
    }

    @Override
    public Integer addAllProduct(PatchGroupProductAddAllProductRequest addAllProductRequest) {
        log.info("-----进入选择保存促销活动商品--远程调用商品服务，查询子商品--productIds:{}-----");
        Long promotionId =addAllProductRequest.getPromotionId();
        GoodsPageQueryRequest goodsPageQueryRequest =new GoodsPageQueryRequest();

//        goodsPageQueryRequest.setMerchantIds(addAllProductRequest.getMerchantIds());
        goodsPageQueryRequest.setId(addAllProductRequest.getId());
        goodsPageQueryRequest.setGoodsCategory(addAllProductRequest.getGoodsCategory());
        goodsPageQueryRequest.setGoodsName(addAllProductRequest.getGoodsName());

        AdminOperate adminOperate = addAllProductRequest.getAdminOperate();
        DeptTypeEnums deptType = adminOperate.getDeptType();
        List<Long> childIds = null;
        List<Long> merchantIds = null;
        List<Long> storeIds = null;
        // 根据平台判断数据权限   开始
        if(deptType != null){
            Long bizId = adminOperate.getBusinessId();
            //母平台
            if(deptType.equals(DeptTypeEnums.OPERATION_PLATFORM)) {
                childIds = adminOperate.getChildIds();
                merchantIds = adminOperate.getMerchantIds();
                storeIds = adminOperate.getStoreIds();
                if (CollectionUtils.isEmpty(merchantIds)) {
                    return DbEffectConstant.SELECT_NOT_FOUND;
                }
                if (CollectionUtils.isEmpty(storeIds)) {
                    return DbEffectConstant.SELECT_NOT_FOUND;
                }
            }
            else if(deptType.equals(DeptTypeEnums.CHILD_PLATFORM)){
                childIds = Arrays.asList(bizId);
                merchantIds = adminOperate.getMerchantIds();
                storeIds = adminOperate.getStoreIds();
                if (CollectionUtils.isEmpty(merchantIds)) {
                    return DbEffectConstant.SELECT_NOT_FOUND;
                }
                if (CollectionUtils.isEmpty(storeIds)) {
                    return DbEffectConstant.SELECT_NOT_FOUND;
                }
            }else if(deptType.equals(DeptTypeEnums.MERCHANT_PLATFORM)){
                merchantIds = Arrays.asList(bizId);
                storeIds = adminOperate.getStoreIds();
                if(CollectionUtils.isEmpty(merchantIds)){
                    return DbEffectConstant.SELECT_NOT_FOUND;
                }
                if(CollectionUtils.isEmpty(storeIds)){
                    return DbEffectConstant.SELECT_NOT_FOUND;
                }
            }else if(deptType.equals(DeptTypeEnums.STORE_PLATFORM)){
                storeIds = Arrays.asList(bizId);
                if(CollectionUtils.isEmpty(storeIds)){
                    return DbEffectConstant.SELECT_NOT_FOUND;
                }
            }
        }

        // 根据平台判断数据权限   结束

//        goodsPageQueryRequest.setChildIds(childIds);
        goodsPageQueryRequest.setStoreIds(addAllProductRequest.getStoreIds());

        List<ProductStoreInfo> productStoreInfos = productListApi.queryProductBySpuList(goodsPageQueryRequest);

//        RestResult<List<GoodsPageQueryResponse>> listRestResult = goodsQueryService.queryByAllCondition(goodsPageQueryRequest);

//        List<GoodsPageQueryResponse> productAfterList = listRestResult.getData();

        if (productStoreInfos == null || productStoreInfos.size() ==0){
            log.info("-----进入选择保存促销活动商品--当前并未查到商品用于促销--promotionId:{}---",promotionId);
            return 2;
        }
        List<PatchGroupProductSaveV2Request> collect = productStoreInfos.stream().map(p -> {
            PatchGroupProductSaveV2Request request = new PatchGroupProductSaveV2Request();
            request.setGoodsSpuId(p.getId());
            request.setPromotionId(addAllProductRequest.getPromotionId());
            return request;
        }).collect(Collectors.toList());
        return this.saveBatchV2(collect);

//        // 组装productList
//        List<PatchGrouponMpEntity> productListNew =new ArrayList<>();
//        for (GoodsPageQueryResponse queryGoodsInfoResponse : productAfterList) {
//            GoodsQueryInfo productAfterResponse = queryGoodsInfoResponse.getGoodsInfo();
//            List<GoodsSkuPageQueryResponse> productAfterSonResponse = queryGoodsInfoResponse.getSkuInfoList();
//
//            /**
//             * TODO 保存 spu商品，赋值类型，数据库字段 type_of_product，参见
//             * ({@link com.jic.market.common.enums.TypeOfProductEnum})
//             */
//
//            log.info("--------spu商品--------");
//            MpQueryUniqueCondition mpQueryUniqueCondition =new MpQueryUniqueCondition();
//            mpQueryUniqueCondition.setMpId(productAfterResponse.getId());
//            mpQueryUniqueCondition.setPromotionId(promotionId);
//            mpQueryUniqueCondition.setStoreId(productAfterResponse.getStoreId());
//            mpQueryUniqueCondition.setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
//            PatchGrouponMpEntity entity = curMapper.getMpQueryUnique(mpQueryUniqueCondition);
//
//            if (null == entity) {
//                PatchGrouponMpEntity productEntity = assembleSpuPromotionProductForAll(promotionId, productAfterResponse);
//                productListNew.add(productEntity);
//            }
//
//            log.info("--------sku商品--------");
//            for (GoodsSkuPageQueryResponse goodsSkuPageQueryResponse : productAfterSonResponse) {
//                GoodsQueryInfo afterSonResponse=goodsSkuPageQueryResponse.getGoodsInfo();
//                MpQueryUniqueCondition mpQueryUniqueConditionSon =new MpQueryUniqueCondition();
//                mpQueryUniqueConditionSon.setMpId(afterSonResponse.getId());
//                mpQueryUniqueConditionSon.setPromotionId(promotionId);
//                mpQueryUniqueConditionSon.setStoreId(afterSonResponse.getStoreId());
//                mpQueryUniqueConditionSon.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
//                PatchGrouponMpEntity entitySon = curMapper.getMpQueryUnique(mpQueryUniqueConditionSon);
//                if (null == entitySon) {
//                    PatchGrouponMpEntity productEntityForSon =
//                            assembleSkuPromotionProductForAll(promotionId, productAfterResponse, afterSonResponse);
//                    productListNew.add(productEntityForSon);
//                }
//
//            }
//        }
//
//        if(productListNew == null || productListNew.size() ==0){
//            log.info("-----当前无促销商品可以保存--promotionId:{}---",promotionId);
//            return 2;
//        }
//
//        // 批量保存 实体
//        List<PatchGrouponMpEntity> productListDB = this.saveBatchEntity(productListNew);
//
//        // 用于添加到patch_groupon_stock_lmt ，需要指定TypeOfProduct为GOODS:商品
//        log.info("----进入批量保存促销活动商品--添加促销商品的限制项--当前促销id:{}--",promotionId);
//        for (PatchGrouponMpEntity promotionProduct : productListDB){
//            LimitQueryUniqueCondition limitCondition =new LimitQueryUniqueCondition();
//            limitCondition.setStoreId(promotionProduct.getStoreId());
//            limitCondition.setTypeOfProduct(promotionProduct.getTypeOfProduct());
//            limitCondition.setPromotionId(promotionId);
//            limitCondition.setMpId(promotionProduct.getMpId());
//            PatchGrouponStockLmtEntity dbEntity =
//                    stockLmtEntityService.getEntityLimitQueryUniqueCondition(limitCondition);
//            if(dbEntity != null){
//                continue;
//            }
//            PatchGrouponStockLmtEntity limitEntity =new PatchGrouponStockLmtEntity();
//            limitEntity.setPatchGrouponMpId(promotionProduct.getId());
//            limitEntity.setLimitType(LimitTypeEnum.GOODS.getCode());
//            limitEntity.setRefPatchGrouponTheme(promotionProduct.getPromotionId());
//            limitEntity.setMerchantId(promotionProduct.getMerchantId());
//            limitEntity.setMerchantProductId(promotionProduct.getMpId());
//            limitEntity.setMpCode(promotionProduct.getMpCode());
//            limitEntity.setTypeOfProduct(promotionProduct.getTypeOfProduct());
//            limitEntity.setStoreId(promotionProduct.getStoreId());
//            //
//            limitEntity.setTypeOfProduct(promotionProduct.getTypeOfProduct());
////            limitEntity.setStoreName(promotionProduct.getStoreName());
//            limitEntity.setMerchantProductName(promotionProduct.getMpName());
//            limitEntity.setRuleType(PatchGrouponStockLmtConstant.RuleType.SHARE.getCode());
//
//            // 限制值的初始化
//            limitEntity.setGrouponPrice(PatchGrouponStockLimitConstant.GROUPON_PRICE);
//            limitEntity.setChannelMerchantLimit(PatchGrouponStockLimitConstant.CHANNEL_MERCHANT_LIMIT);
//            limitEntity.setChannelStoreLimit(PatchGrouponStockLimitConstant.CHANNEL_STORE_LIMIT);
//            limitEntity.setIndividualLimit(PatchGrouponStockLimitConstant.INDIVIDUAL_LIMIT);
//            limitEntity.setOrderLimit(PatchGrouponStockLimitConstant.ORDER_LIMIT);
//            stockLmtEntityService.addPromotionLimitRule(limitEntity);
//        }
//
//        return null;

    }


    private PatchGrouponMpEntity assembleSpuPromotionProduct(Long promotionId, ProductStoreInfo goodsSpuInfo) {
        PatchGrouponMpEntity productEntity =new PatchGrouponMpEntity();
        productEntity.setMpId(goodsSpuInfo.getId());
        productEntity.setPromotionId(promotionId);
        productEntity.setMpCode(goodsSpuInfo.getCode());
        productEntity.setMpName(goodsSpuInfo.getChineseName());
        productEntity.setMpParentId(0L);
        //系列主品
        productEntity.setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
//        productEntity.setBarcode(goodsSpuInfo.getBarCode());
//            productEntity.setBarcodeId(productAfterResponse);
//        productEntity.setCategoryId(productAfterResponse.getCategoryId());
        productEntity.setCategoryName(goodsSpuInfo.getCategoryName());
        productEntity.setMerchantId(goodsSpuInfo.getMerchantId());
        // 商铺名称
        productEntity.setMerchantName(goodsSpuInfo.getMerchantName());
        // TODO 需要增加  picUrl
//        productEntity.setPicUrl(goodsSpuInfo.getPictureUrl());
        productEntity.setScopeType(ProductScopeTypeEnum.PRODUCT.getCode());

//        productEntity.setSalePriceWithTax(goodsSpuInfo.getSalePriceScope());
        productEntity.setStoreId(goodsSpuInfo.getStoreId());
        productEntity.setSalePriceScope(goodsSpuInfo.getSalePriceWithTax().toString());
        // 需要增加 thirdSpuSkuId 字段
        productEntity.setThirdSpuSkuId(goodsSpuInfo.getCode());
//        productEntity.setChildId(req);
        // 店铺名称
        productEntity.setStoreName(goodsSpuInfo.getStoreName());

        productEntity.setMutexFlag(MutexFlagEnum.UN_MUTEX.getCode());
        productEntity.setStatus(0);
        productEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        productEntity.setCreateTime(new Date());
        productEntity.setUpdateTime(new Date());
        return productEntity;
    }

    private PatchGrouponMpEntity assembleSpuPromotionProductForAll(Long promotionId, GoodsQueryInfo goodsSpuInfo) {
        PatchGrouponMpEntity productEntity =new PatchGrouponMpEntity();
        productEntity.setMpId(goodsSpuInfo.getId());
        productEntity.setPromotionId(promotionId);
        productEntity.setMpCode(goodsSpuInfo.getThirdId());
        productEntity.setMpName(goodsSpuInfo.getGoodsName());
        productEntity.setMpParentId(0L);
        //系列主品
        productEntity.setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
//        productEntity.setBarcode(goodsSpuInfo.getBarCode());
//            productEntity.setBarcodeId(productAfterResponse);
//        productEntity.setCategoryId(productAfterResponse.getCategoryId());
        productEntity.setCategoryName(goodsSpuInfo.getGoodsCategory());
        productEntity.setMerchantId(goodsSpuInfo.getMerchantId());
        // 商家名称
        productEntity.setMerchantName(goodsSpuInfo.getMerchantName());
        // TODO 需要增加 picUrl
//        productEntity.setPicUrl(goodsSpuInfo.getPictureUrl());
        productEntity.setScopeType(ProductScopeTypeEnum.PRODUCT.getCode());
        // TODO 需要增加 salePrice, childId 字段
//        productEntity.setSalePriceWithTax(goodsSpuInfo.getSalePriceScope());
        // 价格范围salePriceScope
        productEntity.setSalePriceScope(goodsSpuInfo.getSalePriceScope());
        // 第三方编码 thirdSpuSkuId
        productEntity.setThirdSpuSkuId(goodsSpuInfo.getThirdId());
        productEntity.setStoreId(goodsSpuInfo.getStoreId());
        // 店铺名称
        productEntity.setStoreName(goodsSpuInfo.getStoreName());


        productEntity.setMutexFlag(MutexFlagEnum.UN_MUTEX.getCode());
        productEntity.setStatus(0);
        productEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        productEntity.setCreateTime(new Date());
        productEntity.setUpdateTime(new Date());
        return productEntity;
    }


    private PatchGrouponMpEntity assembleSkuPromotionProduct(Long promotionId, ProductStoreInfo goodsSpuInfo, ProductStoreInfo goodsSkuInfo) {
        PatchGrouponMpEntity productEntityForSon =new PatchGrouponMpEntity();
        productEntityForSon.setMpId(goodsSkuInfo.getId());
        productEntityForSon.setPromotionId(promotionId);
        productEntityForSon.setMpCode(goodsSkuInfo.getCode());
        productEntityForSon.setMpName(goodsSkuInfo.getChineseName());
        productEntityForSon.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());

        productEntityForSon.setMpParentId(goodsSpuInfo.getId());
//        productEntityForSon.setBarcode(goodsSkuInfo.getBarCode());
//        productEntityForSon.setBarcodeId(goodsSkuInfo);
//        productEntityForSon.setCategoryId(goodsSkuInfo.getCategoryId());
        productEntityForSon.setCategoryName(goodsSkuInfo.getCategoryName());
        productEntityForSon.setMerchantId(goodsSkuInfo.getMerchantId());
        // 商铺名称
        productEntityForSon.setMerchantName(goodsSkuInfo.getMerchantName());
//        TODO 需要增加 picUrl
// productEntityForSon.setPicUrl(goodsSkuInfo.getPictureUrl());
        productEntityForSon.setScopeType(ProductScopeTypeEnum.PRODUCT.getCode());

//        productEntityForSon.setSalePriceWithTax(goodsSkuInfo.getSalePrice());
        productEntityForSon.setSalePrice(goodsSkuInfo.getSalePriceWithTax());
        // 保留两位小数
        productEntityForSon.setSalePriceScope(String.valueOf(goodsSkuInfo.getSalePriceWithTax().setScale(2, BigDecimal.ROUND_HALF_UP)));
        // 需要增加 thirdSpuSkuId 字段
        productEntityForSon.setThirdSpuSkuId(goodsSkuInfo.getCode());
//        productEntityForSon.setChildId(goodsSkuInfo.getChildId());
        productEntityForSon.setStoreId(goodsSkuInfo.getStoreId());
        // 店铺名称
        productEntityForSon.setStoreName(goodsSkuInfo.getStoreName());

        productEntityForSon.setMutexFlag(MutexFlagEnum.UN_MUTEX.getCode());
        productEntityForSon.setStatus(0);
        productEntityForSon.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        productEntityForSon.setCreateTime(new Date());
        productEntityForSon.setUpdateTime(new Date());
        return productEntityForSon;
    }

    private PatchGrouponMpEntity assembleSkuPromotionProductForAll(Long promotionId, GoodsQueryInfo goodsSpuInfo, GoodsQueryInfo goodsSkuInfo) {
        PatchGrouponMpEntity productEntityForSon =new PatchGrouponMpEntity();
        productEntityForSon.setMpId(goodsSkuInfo.getId());
        productEntityForSon.setPromotionId(promotionId);
//        productEntityForSon.setMpCode(goodsSkuInfo.getCode());
        productEntityForSon.setMpName(goodsSkuInfo.getGoodsName());
        productEntityForSon.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());

        productEntityForSon.setMpParentId(goodsSpuInfo.getId());
//        productEntityForSon.setBarcode(goodsSkuInfo.getBarCode());
//        productEntityForSon.setBarcodeId(goodsSkuInfo);
//        productEntityForSon.setCategoryId(goodsSkuInfo.getCategoryId());
        productEntityForSon.setCategoryName(goodsSkuInfo.getGoodsCategory());
        // merchantId
        productEntityForSon.setMerchantId(goodsSkuInfo.getMerchantId());
        // 商家名称
        productEntityForSon.setMerchantName(goodsSkuInfo.getMerchantName());
//        productEntityForSon.setPicUrl(goodsSkuInfo.getPictureUrl());
        productEntityForSon.setScopeType(ProductScopeTypeEnum.PRODUCT.getCode());

//        productEntityForSon.setSalePriceWithTax(goodsSkuInfo.getSalePrice());
        // thirdSpuSkuId 字段
        productEntityForSon.setThirdSpuSkuId(goodsSkuInfo.getThirdId());
        productEntityForSon.setSalePrice(new BigDecimal(goodsSkuInfo.getSalePriceScope()));
        productEntityForSon.setSalePriceScope(goodsSkuInfo.getSalePriceScope());
        productEntityForSon.setChildId(goodsSkuInfo.getChildId());
        // storeId
        productEntityForSon.setStoreId(goodsSkuInfo.getStoreId());
        productEntityForSon.setMerchantId(goodsSkuInfo.getMerchantId());
        // 店铺名称
        productEntityForSon.setStoreName(goodsSkuInfo.getStoreName());


        productEntityForSon.setMutexFlag(MutexFlagEnum.UN_MUTEX.getCode());
        productEntityForSon.setStatus(0);
        productEntityForSon.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        productEntityForSon.setCreateTime(new Date());
        productEntityForSon.setUpdateTime(new Date());
        return productEntityForSon;
    }

    @Override
    public List<PatchGrouponMpEntity> findOfPage(
            PatchGrouponMpEntity productCondition,
            Pagination pagination) {
        return curMapper.findOfPage(productCondition,pagination);
    }

    @Override
    public List<PatchGrouponMpEntity> findMutexOfPage(
            PatchGrouponMpEntity productCondition,
            Pagination pagination) {
        return curMapper.findMutexOfPage(productCondition,pagination);
    }

    @Override
    public Integer countOfPage(
            PatchGrouponMpEntity productCondition) {
        return curMapper.countOfPage(productCondition);
    }

    @Override
    public Integer countMutexOfPage(
            PatchGrouponMpEntity productCondition) {
        return curMapper.countMutexOfPage(productCondition);
    }

    @Override
    public Integer deleteProductBatch(List<PatchGouponProductRequest> pgprList) {
        pgprList.forEach(x->{
            this.deleteProduct(x.getPromotionId(), x.getMpId());
        });
        return DbEffectConstant.UPDATE_SUCCESS;
    }

    @Override
    public Integer deleteProductBatchV2(List<PatchGouponProductRequest> pgprList) {
        pgprList.forEach(x->{
            this.deleteProductV2(x.getId());
        });
        return DbEffectConstant.UPDATE_SUCCESS;
    }

    @Override
    public Integer deleteEntityListByPromotionIdAndStoreIdsBatch(Long promotionId, List<Long> storeIds) {
        Integer count = curMapper.deleteEntityListByPromotionIdAndStoreIdsBatch(promotionId, storeIds);
        return count;
    }

    @Override
    public Integer update(PatchGouponProductRequest pgpr) {
        PatchGrouponMpEntity entity = new PatchGrouponMpEntity();
        BeanUtils.copyProperties(pgpr, entity);
        return curMapper.update(entity);
    }

    /**
     * 构建entity
     * @param temp
     * @return
     */
    private PatchGrouponMpEntity buildPatchGrouponMpEntity(PatchGouponProductRequest temp){
        PatchGrouponMpEntity p = new PatchGrouponMpEntity();
        p.setPromotionId(temp.getPromotionId());
        p.setMerchantId(temp.getMerchantId());
        p.setMpName(temp.getMpName());
        p.setMpCode(temp.getMpCode());
        p.setMerchantName(temp.getMerchantName());
        p.setCategoryName(temp.getCategoryName());
        p.setCreateTime(new Date());
        p.setMpId(temp.getMpId());
        p.setCategoryId(temp.getCategoryId());
        p.setPicUrl(temp.getPicUrl());
        p.setMpParentId(temp.getMpParentId());
        p.setStoreName(temp.getStoreName());
        p.setSalePriceWithTax(temp.getSalePriceWithTax());
        return p;
    }

    @Override
    public Integer save(PatchGouponProductRequest temp) {
        PatchGrouponMpEntity entity = curMapper.getByPromotionIdAndMpId(temp.getPromotionId(), temp.getMpId());
        if (null != entity) {
            throw new MarketException(MarketErrorCodeEnum.PARAM_ERROR);
        }

        int ret = curMapper.insert(buildPatchGrouponMpEntity(temp));
        if (ret < 1) {
            throw new MarketException(MarketErrorCodeEnum.SQL_ERROR);
        }

        return ret;
    }

    @Override
    public Integer deleteProduct(Long promotionId, Long mpId) {
        Integer count1 =curMapper.deleteEntityByPromotionIdAndMpId(promotionId, mpId);
        Integer count2 =stockLmtEntityService.deleteEntityByPromotionIdAndMpId(promotionId, mpId);
        return count1;
    }

    @Override
    public Integer deleteProductV2(Long patchGrouponMpId) {
        PatchGrouponMpEntity var1 =new PatchGrouponMpEntity();
        var1.setId(patchGrouponMpId);
        PatchGrouponMpEntity entity = curMapper.query(var1);
        if (entity == null){
            log.info("------删除促销商品--该商品已经不存在--促销商品patch_groupon_mp_id-{}----", patchGrouponMpId);
            return DbEffectConstant.SELECT_NOT_FOUND;
        }
        //是否存在未删除的互斥商品
        AtomicBoolean mutexFlag = new AtomicBoolean(false);
        //  如果是 spu 则找到其下 sku List删除掉
        if(TypeOfProductEnum.GOODS_SPU.getCode().equals(entity.getTypeOfProduct())){
            PatchGrouponMpEntity mpListCondition =new PatchGrouponMpEntity();
            mpListCondition.setMpParentId(entity.getMpId());
            mpListCondition.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
            mpListCondition.setPromotionId(entity.getPromotionId());
            List<PatchGrouponMpEntity> skuMpList = curMapper.findAll(mpListCondition);
            for (PatchGrouponMpEntity patchGrouponMpEntity : skuMpList) {
                if(MutexFlagEnum.MUTEX.getCode().equals(patchGrouponMpEntity.getMutexFlag())&& DeleteFlagEnum.UN_DELETE.getCode().equals(patchGrouponMpEntity.getDeleteFlag())){
                    mutexFlag.set(true);
                }else{
                    curMapper.delete(patchGrouponMpEntity.getId());
                    stockLmtEntityService.deleteByPatchGrouponMpId(patchGrouponMpEntity.getId());
                }
            }
            if(!mutexFlag.get()){
                curMapper.delete(patchGrouponMpId);
                stockLmtEntityService.deleteByPatchGrouponMpId(patchGrouponMpId);
            }
            return 1;
        }

        // 如果是 sku 则看其是否是最后一个 sku，如果是，则找到 spu 一同删除，如果不是仅删除 当前 sku
        else {
            PatchGrouponMpEntity mpListCondition =new PatchGrouponMpEntity();
            mpListCondition.setMpParentId(entity.getMpParentId());
            mpListCondition.setPromotionId(entity.getPromotionId());
            mpListCondition.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
            List<PatchGrouponMpEntity> skuMpList = curMapper.findAll(mpListCondition);
            if(skuMpList.size() == 1){
                // 查找 spu
                PatchGrouponMpEntity spuCondition =new PatchGrouponMpEntity();
                spuCondition.setMpId(entity.getMpParentId());
                spuCondition.setPromotionId(entity.getPromotionId());
                spuCondition.setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
                PatchGrouponMpEntity spuEntity = curMapper.query(spuCondition);
                curMapper.delete(spuEntity.getId());
                stockLmtEntityService.deleteByPatchGrouponMpId(spuEntity.getId());
            }
            curMapper.delete(patchGrouponMpId);
            stockLmtEntityService.deleteByPatchGrouponMpId(patchGrouponMpId);
            return 1;
        }

    }

    @Override
    public ExcelListenerData importMpExcel(MultipartFile excel, Long promotionId, BaseRowModel rowModel) {
        if (excel == null) {
            log.error("请传入正确的excel格式");
            return null;
        }

        GrouponExcelListener excelListener = new GrouponExcelListener();
        ExcelListenerData elData = ExcelUtil.readExcelElData(excelListener, excel, rowModel, 1);

        List<PatchGrouponMpEntity> mpList =new ArrayList<>();
        // 对于正确的信息进行处理
        elData.getDatas().forEach(x->{
            PatchGrouponMpEntity mp =(PatchGrouponMpEntity)x;
            mp.setPromotionId(promotionId);
            mp.setMutexFlag(MutexFlagEnum.UN_MUTEX.getCode());
            mp.setStatus(0);
            mp.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            mp.setCreateTime(new Date());
            mp.setUpdateTime(new Date());
//            curMapper.insert(mp);
            mpList.add(mp);
        });
        log.info("-----mpList{}-----", mpList);

        curMapper.batchSaveMp(mpList);
        // 对于错误的信息进行处理

        return elData;
    }

    @Override
    public List<PatchGrouponMpEntity> saveBatchEntity(List<PatchGrouponMpEntity> productList) {
        log.info("============saveBatchV2-productList={}",productList);
        if (null == productList || productList.isEmpty()) {
            return null;
        }
        // 批量保存
        curMapper.batchSaveMp(productList);

//        List<PatchGrouponMpEntity> entityListNew =new ArrayList<>();
//        for (PatchGrouponMpEntity entity : productList) {
//            curMapper.insert(entity);
//            entityListNew.add(entity);
//        }
        log.info("============saveBatchV2-after");
        return productList;

    }

    @Override
    public PageResult<PatchGroupProductV2Response> getPromotionProductListV2(PatchGroupPromotionProductQueryListV2Request ppqlRequest) {
        PageResult<PatchGroupProductV2Response> responsePageResponse =new PageResult<>();

        PatchGrouponMpEntity condition =new PatchGrouponMpEntity();
        BeanUtils.copyProperties(ppqlRequest,condition);
        Pagination pagination =Pagination.build(ppqlRequest.getStart(), ppqlRequest.getLimit());

//        Pagination pagination =new Pagination();
//        pagination.setLimitStart((ppqlRequest.getStart()-1) * ppqlRequest.getLimit());
//        pagination.setPageSize(ppqlRequest.getLimit());


        AdminOperate adminOperate = ppqlRequest.getAdminOperate();
        DeptTypeEnums deptType = adminOperate.getDeptType();
        List<Long> merchantIds = null;
        List<Long> storeIds = null;
        // 根据平台判断数据权限   开始
//        if(deptType != null){
//            Long bizId = adminOperate.getBusinessId();
//            //母平台
//            if(deptType.equals(DeptTypeEnums.OPERATION_PLATFORM) || deptType.equals(DeptTypeEnums.CHILD_PLATFORM)){
//                merchantIds = adminOperate.getMerchantIds();
//                storeIds = adminOperate.getStoreIds();
//                if(CollectionUtils.isEmpty(merchantIds)){
//                    responsePageResponse.setTotal(0L);
//                    return responsePageResponse;
//                }
//                if(CollectionUtils.isEmpty(storeIds)){
//                    responsePageResponse.setTotal(0L);
//                    return responsePageResponse;
//                }
//            }else if(deptType.equals(DeptTypeEnums.MERCHANT_PLATFORM)){
//                merchantIds = Arrays.asList(bizId);
//                storeIds = adminOperate.getStoreIds();
//                if(CollectionUtils.isEmpty(merchantIds)){
//                    responsePageResponse.setTotal(0L);
//                    return responsePageResponse;
//                }
//                if(CollectionUtils.isEmpty(storeIds)){
//                    responsePageResponse.setTotal(0L);
//                    return responsePageResponse;
//                }
//            }else if(deptType.equals(DeptTypeEnums.STORE_PLATFORM)){
//                storeIds = Arrays.asList(bizId);
//                if(CollectionUtils.isEmpty(storeIds)){
//                    responsePageResponse.setTotal(0L);
//                    return responsePageResponse;
//                }
//            }
//        }

        // 根据平台判断数据权限   结束

//        condition.setMerchantIds(merchantIds);
//        condition.setStoreIds(storeIds);
        condition.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        condition.setCreatorName(null);
        condition.setCreator(null);
        condition.setUpdator(null);
        condition.setUpdatorName(null);
        // 只查SPU
        condition.setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
        List<PatchGrouponMpEntity> productList = findMutexOfPage(condition, pagination);
        Integer count = this.countMutexOfPage(condition);
        List<PatchGroupProductV2Response> responseList = null;
        if(productList !=null && !productList.isEmpty()){
            responseList = ListUtils.entityListToModelList(
                    productList, PatchGroupProductV2Response.class);
        }


        if(responseList !=null && !responseList.isEmpty()){
            for (PatchGroupProductV2Response pp : responseList) {

//                RestResult<List<GoodsSpuPageQueryResponse>> listRestResult = goodsQueryService.querySpu(new ArrayList<Long>() {{
//                    add(pp.getMpId());
//                }});
                List<ProductStoreInfo> productStoreInfos = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                    setId(pp.getMpId());
                }});
                pp.setStock(productStoreInfos.get(0).getAvailableStock().intValue());
                pp.setSalePriceScope(productStoreInfos.get(0).getSalePriceWithTax().toString());

                PatchGrouponMpEntity conditionSon =new PatchGrouponMpEntity();
//                BeanUtils.copyProperties(ppqlRequest,conditionSon);
                Pagination paginationSon =Pagination.build(1, 100);


                conditionSon.setPromotionId(ppqlRequest.getPromotionId());
                conditionSon.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                conditionSon.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
                // 父商品id
                conditionSon.setMpParentId(pp.getMpId());
                conditionSon.setMutexFlag(ppqlRequest.getMutexFlag());
                List<PatchGrouponMpEntity> productListSon = this.
                        findOfPage(conditionSon, paginationSon);

                List<PatchGroupSonProductV2Response> responseListSon = null;
                if (productListSon !=null && !productListSon.isEmpty()){
                    responseListSon = ListUtils.entityListToModelList(
                            productListSon, PatchGroupSonProductV2Response.class);
                }

                if(responseListSon !=null && !responseListSon.isEmpty()){
                    for (PatchGroupSonProductV2Response ppSon : responseListSon) {

//                        RestResult<List<GoodsSkuQueryResponse>> listRestResult1 = goodsQueryService.querySku(new ArrayList<Long>() {{
//                            add(ppSon.getMpId());
//                        }});

                        List<ProductStoreInfo> productStoreInfosVo = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                            setId(ppSon.getMpId());
                        }});

                        ppSon.setStock(productStoreInfosVo.get(0).getAvailableStock().intValue());
                        ppSon.setSalePriceScope(productStoreInfosVo.get(0).getSalePriceWithTax().toString());
//                        PromotionLimitRuleEntity promotionLimitRuleSon = stockLmtEntityService.getEntityLimitQueryUniqueCondition(ppSon.getPromotionId(), ppSon.getMpId());
                        LimitQueryUniqueCondition limitQueryUniqueConditionSon =new LimitQueryUniqueCondition();
                        limitQueryUniqueConditionSon.setMpId(ppSon.getMpId());
                        limitQueryUniqueConditionSon.setTypeOfProduct(ppSon.getTypeOfProduct());
                        limitQueryUniqueConditionSon.setPromotionId(ppSon.getPromotionId());
                        limitQueryUniqueConditionSon.setStoreId(ppSon.getStoreId());
                        PatchGrouponStockLmtEntity promotionLimitRuleSon = stockLmtEntityService.
                                getEntityLimitQueryUniqueCondition(limitQueryUniqueConditionSon);
                        if(promotionLimitRuleSon !=null){
                            ppSon.setPlatformTotalLimit(promotionLimitRuleSon.getPlatformTotalLimit());
                            ppSon.setChannelMerchantLimit(promotionLimitRuleSon.getChannelMerchantLimit());
                            ppSon.setChannelStoreLimit(promotionLimitRuleSon.getChannelStoreLimit());
                            ppSon.setChannelMerchantLimit(promotionLimitRuleSon.getChannelMerchantLimit());
                            ppSon.setTotalLimit(promotionLimitRuleSon.getTotalLimit());
                            ppSon.setIndividualLimit(promotionLimitRuleSon.getIndividualLimit());
                            ppSon.setOrderLimit(promotionLimitRuleSon.getOrderLimit());
                            ppSon.setLimitRuleId(promotionLimitRuleSon.getId());
                            ppSon.setGrouponPrice(promotionLimitRuleSon.getGrouponPrice());
                            ppSon.setParentAllocationScale(promotionLimitRuleSon.getParentAllocationScale());
                            ppSon.setMerchantAllocationScale(promotionLimitRuleSon.getMerchantAllocationScale());
                            ppSon.setStockLimit(promotionLimitRuleSon.getStockLimit());
                        }
                    }
                }

                pp.setChildren(responseListSon);
//                PromotionLimitRuleEntity promotionLimitRule = stockLmtEntityService.getEntityByPromotionIdAndMpId(pp.getPromotionId(), pp.getMpId());
                LimitQueryUniqueCondition limitQueryUniqueCondition =new LimitQueryUniqueCondition();
                limitQueryUniqueCondition.setMpId(pp.getMpId());
                limitQueryUniqueCondition.setTypeOfProduct(pp.getTypeOfProduct());
                limitQueryUniqueCondition.setPromotionId(pp.getPromotionId());
                limitQueryUniqueCondition.setStoreId(pp.getStoreId());

                PatchGrouponStockLmtEntity promotionLimitRule = stockLmtEntityService.getEntityLimitQueryUniqueCondition(limitQueryUniqueCondition);

                if (promotionLimitRule !=null){
                    pp.setPlatformTotalLimit(promotionLimitRule.getPlatformTotalLimit());
                    pp.setChannelMerchantLimit(promotionLimitRule.getChannelMerchantLimit());
                    pp.setChannelStoreLimit(promotionLimitRule.getChannelStoreLimit());
                    pp.setTotalLimit(promotionLimitRule.getTotalLimit());
                    pp.setIndividualLimit(promotionLimitRule.getIndividualLimit());
                    pp.setOrderLimit(promotionLimitRule.getOrderLimit());
                    pp.setLimitRuleId(promotionLimitRule.getId());
                    pp.setGrouponPrice(promotionLimitRule.getGrouponPrice());
                    pp.setParentAllocationScale(promotionLimitRule.getParentAllocationScale());
                    pp.setMerchantAllocationScale(promotionLimitRule.getMerchantAllocationScale());
                    pp.setStockLimit(promotionLimitRule.getStockLimit());
                }

            }
        }

        PageResult<PatchGroupProductV2Response> pageResult =new PageResult<>();
        pageResult.setRows(responseList);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public PageResult<GrouponProductInfo> getMpListForRest(GrouponProductListRequest request) {
        PatchGrouponMpEntity condition =new PatchGrouponMpEntity();
        condition.setPromotionId(request.getPromotionId());
        Pagination pagination =Pagination.build(request.getStart(), request.getLimit());

        condition.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        // 当想查特定的商品需要此值
        condition.setThirdSpuSkuId(request.getThirdProductCode());
        condition.setCreatorName(null);
        condition.setCreator(null);
        condition.setUpdator(null);
        condition.setUpdatorName(null);
        condition.setMutexFlag(0);
        // 只查SKU
        condition.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
        List<PatchGrouponMpEntity> productList = this.findOfPage(condition, pagination);
        Integer count = this.countOfPage(condition);

        List<GrouponProductInfo> responseList = new ArrayList<>();
        for (PatchGrouponMpEntity mpDb : productList) {
            GrouponProductInfo productInfo =new GrouponProductInfo();
            productInfo.setMarketPrice(mpDb.getSalePrice());
            productInfo.setMpName(mpDb.getMpName());
            productInfo.setThirdProductCode(mpDb.getThirdSpuSkuId());

            LimitQueryUniqueCondition limitQueryUniqueCondition =new LimitQueryUniqueCondition();
            limitQueryUniqueCondition.setMpId(mpDb.getMpId());
            limitQueryUniqueCondition.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
            limitQueryUniqueCondition.setPromotionId(mpDb.getPromotionId());
            limitQueryUniqueCondition.setStoreId(mpDb.getStoreId());
            PatchGrouponStockLmtEntity promotionLimitRule = stockLmtEntityService.getEntityLimitQueryUniqueCondition(limitQueryUniqueCondition);

            if (promotionLimitRule !=null){
                productInfo.setAvailablePrice(promotionLimitRule.getGrouponPrice());
            }
            responseList.add(productInfo);
        }
        
//        List<PatchGroupProductV2Response> responseList2 = null;

        PageResult<GrouponProductInfo> pageResult =new PageResult<>();
        pageResult.setRows(responseList);
        pageResult.setTotal(count);
        return pageResult;
    }


    @Override
    public Long skuCount(PatchGrouponProductSkuCountRequest request) {
        PatchGrouponMpEntity productCondition =new PatchGrouponMpEntity();
        productCondition.setPromotionId(request.getPromotionId());
        productCondition.setMerchantId(request.getMerchantId());
        productCondition.setThirdSpuSkuId(request.getThirdSpuSkuId());
        productCondition.setMpName(request.getMpName());
        productCondition.setCategoryName(request.getCategoryName());
        productCondition.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
        productCondition.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        productCondition.setMutexFlag(request.getMutexFlag());
        AdminOperate adminOperate = request.getAdminOperate();
        DeptTypeEnums deptType = adminOperate.getDeptType();
        List<Long> merchantIds = null;
        List<Long> storeIds = null;

        // 根据平台判断数据权限   开始
        if(deptType != null){
            Long bizId = adminOperate.getBusinessId();
            //母平台
            if(deptType.equals(DeptTypeEnums.OPERATION_PLATFORM) || deptType.equals(DeptTypeEnums.CHILD_PLATFORM)){
                merchantIds = adminOperate.getMerchantIds();
                storeIds = adminOperate.getStoreIds();
            }else if(deptType.equals(DeptTypeEnums.MERCHANT_PLATFORM)){
                merchantIds = Arrays.asList(bizId);
                storeIds = adminOperate.getStoreIds();
            }else if(deptType.equals(DeptTypeEnums.STORE_PLATFORM)){
                storeIds = Arrays.asList(bizId);
            }
        }

        productCondition.setStoreIds(storeIds);
        Integer count = this.countOfPage(productCondition);
        return Long.valueOf(count);
    }
}
